import { ref, computed } from 'vue'
import type {
    DictionaryCategory,
    DictionaryItem,
    DictionaryCategoryForm,
    DictionaryItemForm,
    DictionaryFilter,
    DictionaryPage
} from '@/types/dictionary'

class DictionaryService {
    // 字典分类数据
    private categories = ref<DictionaryCategory[]>([])

    // 字典项数据
    private items = ref<DictionaryItem[]>([])

    constructor() {
        this.loadFromStorage()
        this.initDefaultData()
    }

    // 从本地存储加载数据
    private loadFromStorage() {
        try {
            const storedCategories = localStorage.getItem('dictionary_categories')
            const storedItems = localStorage.getItem('dictionary_items')

            if (storedCategories) {
                this.categories.value = JSON.parse(storedCategories)
            }
            if (storedItems) {
                this.items.value = JSON.parse(storedItems)
            }
        } catch (error) {
            console.error('加载字典数据失败:', error)
        }
    }

    // 保存数据到本地存储
    private saveToStorage() {
        try {
            localStorage.setItem('dictionary_categories', JSON.stringify(this.categories.value))
            localStorage.setItem('dictionary_items', JSON.stringify(this.items.value))
        } catch (error) {
            console.error('保存字典数据失败:', error)
        }
    }

    // 初始化默认数据
    private initDefaultData() {
        if (this.categories.value.length === 0) {
            const defaultCategories: DictionaryCategory[] = [
                {
                    id: 'site_type',
                    name: '站点类型',
                    code: 'SITE_TYPE',
                    description: '电商平台站点类型分类',
                    sort: 1,
                    status: 'enabled',
                    createdAt: new Date().toISOString(),
                    updatedAt: new Date().toISOString()
                }
            ]

            this.categories.value = defaultCategories

            // 添加默认字典项
            const defaultItems: DictionaryItem[] = [
                // 站点类型
                {
                    id: 'site_amazon',
                    categoryId: 'site_type',
                    name: '亚马逊',
                    code: 'AMAZON',
                    value: 'amazon',
                    label: '亚马逊',
                    description: '亚马逊电商平台',
                    sort: 1,
                    status: 'enabled',
                    isDefault: true,
                    remark: '全球最大的电商平台',
                    createdAt: new Date().toISOString(),
                    updatedAt: new Date().toISOString()
                },
                {
                    id: 'site_rakuten',
                    categoryId: 'site_type',
                    name: '乐天市场',
                    code: 'RAKUTEN',
                    value: 'rakuten',
                    label: '乐天市场',
                    description: '日本乐天市场',
                    sort: 2,
                    status: 'enabled',
                    isDefault: false,
                    remark: '日本知名电商平台',
                    createdAt: new Date().toISOString(),
                    updatedAt: new Date().toISOString()
                },
                {
                    id: 'site_yahoo',
                    categoryId: 'site_type',
                    name: '雅虎日拍',
                    code: 'YAHOO',
                    value: 'yahoo',
                    label: '雅虎日拍',
                    description: '雅虎日本拍卖',
                    sort: 3,
                    status: 'enabled',
                    isDefault: false,
                    remark: '日本拍卖平台',
                    createdAt: new Date().toISOString(),
                    updatedAt: new Date().toISOString()
                }
            ]

            this.items.value = defaultItems
            this.saveToStorage()
        }
    }

    // ==================== 字典分类管理 ====================

    // 获取所有分类
    getCategories(): DictionaryCategory[] {
        return this.categories.value
    }

    // 根据ID获取分类
    getCategoryById(id: string): DictionaryCategory | undefined {
        return this.categories.value.find(cat => cat.id === id)
    }

    // 根据编码获取分类
    getCategoryByCode(code: string): DictionaryCategory | undefined {
        return this.categories.value.find(cat => cat.code === code)
    }



    // 新增分类
    addCategory(category: DictionaryCategoryForm): DictionaryCategory {
        const newCategory: DictionaryCategory = {
            id: `cat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            ...category,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        }

        this.categories.value.push(newCategory)
        this.saveToStorage()
        return newCategory
    }

    // 更新分类
    updateCategory(id: string, category: Partial<DictionaryCategoryForm>): boolean {
        const index = this.categories.value.findIndex(cat => cat.id === id)
        if (index !== -1) {
            this.categories.value[index] = {
                ...this.categories.value[index],
                ...category,
                updatedAt: new Date().toISOString()
            }
            this.saveToStorage()
            return true
        }
        return false
    }

    // 删除分类
    deleteCategory(id: string): boolean {
        // 检查是否有关联的字典项
        const hasItems = this.items.value.some(item => item.categoryId === id)
        if (hasItems) {
            throw new Error('该分类下存在字典项，无法删除')
        }

        const index = this.categories.value.findIndex(cat => cat.id === id)
        if (index !== -1) {
            this.categories.value.splice(index, 1)
            this.saveToStorage()
            return true
        }
        return false
    }

    // ==================== 字典项管理 ====================

    // 获取所有字典项
    getItems(): DictionaryItem[] {
        return this.items.value
    }

    // 根据分类ID获取字典项
    getItemsByCategory(categoryId: string): DictionaryItem[] {
        return this.items.value.filter(item => item.categoryId === categoryId)
    }

    // 根据分类编码获取字典项
    getItemsByCategoryCode(categoryCode: string): DictionaryItem[] {
        const category = this.getCategoryByCode(categoryCode)
        if (category) {
            return this.getItemsByCategory(category.id)
        }
        return []
    }

    // 根据ID获取字典项
    getItemById(id: string): DictionaryItem | undefined {
        return this.items.value.find(item => item.id === id)
    }

    // 根据编码获取字典项
    getItemByCode(code: string): DictionaryItem | undefined {
        return this.items.value.find(item => item.code === code)
    }

    // 新增字典项
    addItem(item: DictionaryItemForm): DictionaryItem {
        const newItem: DictionaryItem = {
            id: `item_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            ...item,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        }

        // 如果设置为默认值，需要将同分类下的其他项设为非默认
        if (item.isDefault) {
            this.items.value.forEach(existingItem => {
                if (existingItem.categoryId === item.categoryId && existingItem.isDefault) {
                    existingItem.isDefault = false
                }
            })
        }

        this.items.value.push(newItem)
        this.saveToStorage()
        return newItem
    }

    // 更新字典项
    updateItem(id: string, item: Partial<DictionaryItemForm>): boolean {
        const index = this.items.value.findIndex(existingItem => existingItem.id === id)
        if (index !== -1) {
            const updatedItem = {
                ...this.items.value[index],
                ...item,
                updatedAt: new Date().toISOString()
            }

            // 如果设置为默认值，需要将同分类下的其他项设为非默认
            if (item.isDefault) {
                this.items.value.forEach(existingItem => {
                    if (existingItem.categoryId === updatedItem.categoryId &&
                        existingItem.id !== id &&
                        existingItem.isDefault) {
                        existingItem.isDefault = false
                    }
                })
            }

            this.items.value[index] = updatedItem
            this.saveToStorage()
            return true
        }
        return false
    }

    // 删除字典项
    deleteItem(id: string): boolean {
        const index = this.items.value.findIndex(item => item.id === id)
        if (index !== -1) {
            this.items.value.splice(index, 1)
            this.saveToStorage()
            return true
        }
        return false
    }

    // 批量删除字典项
    deleteItems(ids: string[]): boolean {
        let success = true
        ids.forEach(id => {
            if (!this.deleteItem(id)) {
                success = false
            }
        })
        return success
    }

    // ==================== 查询和分页 ====================

    // 分页查询字典项
    getItemsWithPagination(
        filter: DictionaryFilter = {},
        page: DictionaryPage
    ): { items: DictionaryItem[], total: number } {
        let filteredItems = [...this.items.value]

        // 应用过滤条件
        if (filter.categoryId) {
            filteredItems = filteredItems.filter(item => item.categoryId === filter.categoryId)
        }
        if (filter.name) {
            filteredItems = filteredItems.filter(item =>
                item.name.toLowerCase().includes(filter.name!.toLowerCase())
            )
        }
        if (filter.code) {
            filteredItems = filteredItems.filter(item =>
                item.code.toLowerCase().includes(filter.code!.toLowerCase())
            )
        }
        if (filter.status) {
            filteredItems = filteredItems.filter(item => item.status === filter.status)
        }

        // 排序
        filteredItems.sort((a, b) => a.sort - b.sort)

        const total = filteredItems.length
        const start = (page.current - 1) * page.size
        const end = start + page.size
        const items = filteredItems.slice(start, end)

        return { items, total }
    }

    // ==================== 工具方法 ====================

    // 获取分类名称
    getCategoryName(categoryId: string): string {
        const category = this.getCategoryById(categoryId)
        return category ? category.name : '未知分类'
    }

    // 获取字典项标签
    getItemLabel(categoryCode: string, value: string): string {
        const items = this.getItemsByCategoryCode(categoryCode)
        const item = items.find(item => item.value === value)
        return item ? item.label : value
    }

    // 获取字典项值
    getItemValue(categoryCode: string, label: string): string {
        const items = this.getItemsByCategoryCode(categoryCode)
        const item = items.find(item => item.label === label)
        return item ? item.value : label
    }

    // 获取分类的字典项选项（用于下拉选择）
    getCategoryOptions(categoryCode: string): { label: string, value: string }[] {
        const items = this.getItemsByCategoryCode(categoryCode)
        return items
            .filter(item => item.status === 'enabled')
            .map(item => ({
                label: item.label,
                value: item.value
            }))
            .sort((a, b) => {
                const itemA = items.find(item => item.value === a.value)
                const itemB = items.find(item => item.value === b.value)
                return (itemA?.sort || 0) - (itemB?.sort || 0)
            })
    }

    // 检查编码是否重复
    isCodeDuplicate(code: string, excludeId?: string): boolean {
        return this.items.value.some(item =>
            item.code === code && item.id !== excludeId
        )
    }

    // 检查分类编码是否重复
    isCategoryCodeDuplicate(code: string, excludeId?: string): boolean {
        return this.categories.value.some(cat =>
            cat.code === code && cat.id !== excludeId
        )
    }
}

// 创建单例实例
const dictionaryService = new DictionaryService()

export default dictionaryService
